package com.google.gwt.sample.stockwatcher.server;

import java.util.Random;

import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.remoting.WebRemote;

import com.google.gwt.sample.stockwatcher.client.DelistedException;
import com.google.gwt.sample.stockwatcher.client.StockPrice;
import com.google.gwt.sample.stockwatcher.client.StockPriceService;

/**
 * <p>Implementation of interface <code>com.google.gwt.sample.stockwatcher.client.StockPriceService</code>.</p>
 * <p>The component name must match the name of implemented interface.</p>
 * 
 * @author dearshor
 *
 */
@Name("com.google.gwt.sample.stockwatcher.client.StockPriceService")
public class StockPriceServiceImpl  implements
		StockPriceService {


	private static final double MAX_PRICE = 100.0; // $100.00
	private static final double MAX_PRICE_CHANGE = 0.02; // +/- 2%

	@WebRemote
	public StockPrice[] getPrices(String[] symbols) throws DelistedException {
		Random rnd = new Random();

		StockPrice[] prices = new StockPrice[symbols.length];
		for (int i = 0; i < symbols.length; i++) {
			if (symbols[i].equals("ERR")) {
				throw new DelistedException("ERR");
			}
			
			if (symbols[i].equals("UNEXPECTED")) {
				throw new RuntimeException("Oops! An unexpected exception occured!!");
			}

			double price = rnd.nextDouble() * MAX_PRICE;
			double change = price * MAX_PRICE_CHANGE
					* (rnd.nextDouble() * 2f - 1f);

			prices[i] = new StockPrice(symbols[i], price, change);
		}

		return prices;

	}

}
